import {Component, OnInit, Input, AfterViewInit, OnDestroy} from '@angular/core';
import {Subscription, timer} from 'rxjs';
import {NavigationEnd, Router} from '@angular/router';
import {filter, first} from 'rxjs/internal/operators';
import {heightSpread, MessageService} from '../../../../../ng-tools';
import {Message} from '../../../../../ng-tools/src/message/message';
import {ThemeService} from '../../../../services/theme.service';

export const heightSpreadTrigger = heightSpread('0', '*', '250ms linear');

export class Menu {
  id: number;
  name: string;
  expandable: boolean;
  css_icon: string;
  bold: boolean;
  link: string;
  active: boolean;
  leaf_node: boolean;
  sub_menu: Menu[] = [];
  supers: number[];
}

@Component({
  selector: 'app-menu-item',
  templateUrl: './menu-item.component.html',
  styleUrls: ['./menu-item.component.scss'],
  animations: [
    heightSpreadTrigger
  ]
})
export class MenuItemComponent implements OnInit, AfterViewInit, Message, OnDestroy {
  subscriptions: Subscription = new Subscription();
  stateExpression = 'start';
  @Input() item: Menu;
  @Input() index;
  @Input() backgroundColor;

  constructor(private messageService: MessageService,
              private router: Router,
              public theme: ThemeService) {
  }

  ngOnInit() {
  }

  get bgColor() {
    return this.theme.colorDarken(this.backgroundColor, 0.05);
  }

  messageHandler() {
    const s1 = this.messageService.getMessage('menu item loaded', this)
      .pipe(first()).subscribe((next) => {
        if (next.data.id === this.item.id || next.data.supers.indexOf(this.item.id) >= 0) {
          this.expandMenuItem();
          this.item.active = true;
        }
      });

    const s2 = this.messageService.getMessage('menu item clicked', this)
      .subscribe((next) => {
        /**
         * 接收菜单点击事件发来的菜单对象
         * */
        const menu = next.data;
        if (menu.id === this.item.id) {
          /** 展开被点击的菜单,并切换到激活状态 */
          this.toggleMenuItem();
        }
      });
    const s3 = this.messageService.getMessage('route navigation end', this)
      .subscribe((next) => {
        next = next.data;
        if (next.id === this.item.id || next.supers.indexOf(this.item.id) >= 0) {
          this.expandMenuItem();
          this.itemActive = true;
        } else {
          this.itemActive = false;
        }
      });
    this.subscriptions.add(s1);
    this.subscriptions.add(s2);
    this.subscriptions.add(s3);
  }

  expandMenuItem() {
    timer(0).subscribe(() => {
      this.stateExpression = 'end';
    });
  }

  // noinspection JSUnusedGlobalSymbols
  collapseMenuItem() {
    timer(100).subscribe(() => {
      this.stateExpression = 'start';
    });
  }

  toggleMenuItem() {
    this.stateExpression = this.stateExpression === 'start' ? 'end' : 'start';
  }

  menuItemClick(): void {
    this.messageService.sendMessage('menu item clicked', this, this.item);
  }

  set itemActive(value: boolean) {
    timer(0).subscribe(() => {
      this.item.active = value;
    });
  }

  ngAfterViewInit(): void {

    if (this.item.link && this.router.routerState.snapshot.url.match(this.item.link)) {
      this.messageService.sendMessage('menu item loaded', this, this.item);
    }

    const routerSub = this.router.events.pipe(filter(value => value instanceof NavigationEnd))
      .subscribe((e) => {
        if (e instanceof NavigationEnd) {
          /** 接收路由加载完成的消息 然后广播当前路由url */
          if (this.item.link && e.urlAfterRedirects.match(this.item.link)) {
            this.messageService.sendMessage('route navigation end', this, this.item);
          }
          this.subscriptions.add(routerSub);
        }
      });

    this.messageHandler();
  }

  ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
  }

}
